package com.carple.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.carple.common.Util;
import com.carple.dao.MemberDao;
import com.carple.dto.Member;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/account/login.action")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		
		//1. 요청 데이터 읽기 (아이디, 비밀번호)
		String id = req.getParameter("id");
		String passwd = req.getParameter("pass");
//		passwd = Util.getHashedString(passwd, "SHA-1");

		//2. 데이터 처리 (db에서 조회)
		MemberDao dao = new MemberDao();
		Member member = dao.getMemberByIdAndPasswd(id, passwd);
		
		
		//3. 결과에 따라 이동 (성공 - home.action, 실패 - loginform.action) (서블릿은 리다이렉트로 보낸다)
		String path = null;
		if(member==null){
			//로그인 실패
			path ="/carple/account/loginform.action";
		}else {
			//로그인 성공
			HttpSession session = req.getSession(); //서블릿에서는 세션이 기본 객체가 아니므로 이렇게 뽑는다
			session.setAttribute("loginuser",member);//로그인 처리
			if(req.getParameter("returnuri")!=null && req.getParameter("returnuri").length() > 0){
				path = req.getParameter("returnuri");
			}
			else{
				path ="/carple/home.action";
			}
		}
		resp.sendRedirect(path); //브라우져가 사용할꺼기 때문에 경로에 appname 써줘야한다.
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		doGet(req,resp);
	}

}
